package com.tckj.boot.modules.domain.sys.dict;

import com.tckj.boot.common.utils.BeanUtils;
import com.tckj.boot.common.utils.QueryHelp;
import com.tckj.boot.modules.domain.sys.dict.dto.DictDetailDTO;
import com.tckj.boot.modules.domain.sys.dict.dto.DictDetailQueryCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
* @author icodebug
* @date 2019-07-08
*/
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class DictDetailService {

    @Autowired
    private DictDetailRepository dictDetailRepository;


    public Object queryAll(DictDetailQueryCriteria criteria, Pageable pageable) {
        Page<DictDetail> page = dictDetailRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return page;
    }

    public DictDetailDTO findById(Long id) {
        Optional<DictDetail> dictDetail = dictDetailRepository.findById(id);
        DictDetailDTO dto =new DictDetailDTO();
        BeanUtils.copyNotNullProperties(dictDetail.get(),dto);
        return dto;
    }

    @Transactional(rollbackFor = Exception.class)
    public DictDetailDTO create(DictDetail resources) {
        DictDetailDTO dto =new DictDetailDTO();
        BeanUtils.copyNotNullProperties(dictDetailRepository.save(resources),dto);
        return dto;
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(DictDetail resources) {
        Optional<DictDetail> optionalDictDetail = dictDetailRepository.findById(resources.getId());

        if (optionalDictDetail.isPresent()){
            DictDetail dictDetail = optionalDictDetail.get();
            BeanUtils.copyNotNullProperties(resources,dictDetail);
            dictDetailRepository.save(resources);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        dictDetailRepository.deleteById(id);
    }
}